Skip to content

AstModel

Base classes

Name Children Inherits
TreeModel
prettyqt.itemmodels.treemodel
TreeModel which is used as a base for most TreeModels implemented.

â‹” Inheritance diagram

graph TD
  3648284048["itemmodels.AstModel"]
  2846913429["itemmodels.TreeModel"]
  874904086["core.AbstractItemModel"]
  3882849576["core.AbstractItemModelMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  1898060022["QtCore.QAbstractItemModel"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  2846913429 --> 3648284048
  874904086 --> 2846913429
  3882849576 --> 874904086
  3227531497 --> 3882849576
  2751680898 --> 3227531497
  2751680898 --> 3882849576
  1898060022 --> 874904086
  3984060476 --> 1898060022
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

Bases: TreeModel

Tree model to display an Abstract syntax tree.

The model shows a tree of all nodes from an abstract syntax tree They are part of the builtin ast module.

Example:

import ast

view = TreeView()
code = pathlib.Path(__file__).read_text("utf-8)
tree = ast.parse(code)
model = AstModel(tree)
view.set_model(model)
Source code in prettyqt/itemmodels/astmodel.py
class AstModel(itemmodels.TreeModel):
    """Tree model to display an Abstract syntax tree.

    The model shows a tree of all nodes from an
    [abstract syntax tree](https://docs.python.org/3/library/ast.html#node-classes)
    They are part of the builtin `ast` module.

    ### Example:
    ```py
    import ast

    view = TreeView()
    code = pathlib.Path(__file__).read_text("utf-8)
    tree = ast.parse(code)
    model = AstModel(tree)
    view.set_model(model)
    ```
    """

    @core.Enum
    class Roles(enum.IntEnum):
        NodeRole = constants.USER_ROLE

    SUPPORTS = ast.AST
    HEADER: ClassVar = [
        "Node type",
        "Name",
        "Line range",
        "Column range",
        "Code segement",
        "Docstring",
    ]

    def __init__(self, ast_tree: ast.AST | str, **kwargs):
        super().__init__(None, **kwargs)
        self.ast_tree = None
        self.code = ""
        self.set_ast(ast_tree)

    @classmethod
    def supports(cls, instance) -> bool:
        return isinstance(instance, ast.AST)

    def columnCount(self, parent=None):
        return len(self.HEADER) if self.ast_tree is not None else 0

    def set_ast(self, ast_tree: ast.AST | str = ""):
        """Set an AST tree for the model.

        Arguments:
            ast_tree: Abstract syntax tree
        """
        match ast_tree:
            case str():
                code = ast_tree
                try:
                    node = ast.parse(ast_tree)
                except SyntaxError as e:
                    logger.debug("caught %r when building AST", e)
                    return
            case ast.AST():
                code = ast.unparse(ast_tree)
                node = ast.parse(code)  # makin a circle to make sure line numbers match.
            case _:
                raise TypeError(ast_tree)
        node = ast.fix_missing_locations(node)
        with self.reset_model():
            self.ast_tree = node
            self._init_root_item(node)
            self.code = code

    # def find_lineno(self, index):
    #     # not needed, thx to ast.fix_missing_locations
    #     while not hasattr(node := index.data(constants.USER_ROLE), "lineno"):
    #         index = index.parent()
    #     return node.lineno

    def headerData(
        self,
        section: int,
        orientation: constants.Orientation,
        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
    ):
        match orientation, role:
            case constants.HORIZONTAL, constants.DISPLAY_ROLE if section < len(
                self.HEADER
            ):
                return self.HEADER[section]
        return None

    def data(self, index: core.ModelIndex, role=constants.DISPLAY_ROLE):  # noqa: PLR0911
        if not index.isValid():
            return None
        node = self.data_by_index(index).obj
        match role, index.column():
            case constants.DISPLAY_ROLE, 0:
                return type(node).__name__
            case constants.DISPLAY_ROLE, 1:
                match node:
                    case _ if type(node) in NODE_MAP:
                        return NODE_MAP[type(node)]
                    case (
                        ast.Name(id=name)
                        | ast.arg(arg=name)
                        | ast.alias(name=name)
                        | ast.ClassDef(name=name)
                        | ast.FunctionDef(name=name)
                    ):
                        return name
                    case ast.Constant(value=value):
                        return repr(value)
            case constants.DISPLAY_ROLE, 2:
                if hasattr(node, "lineno"):
                    return (
                        f"{node.lineno} - {node.end_lineno}"
                        if node.lineno != node.end_lineno
                        else str(node.lineno)
                    )
                return None
            case constants.DISPLAY_ROLE, 3:
                if hasattr(node, "col_offset"):
                    return (
                        f"{node.col_offset} - {node.end_col_offset}"
                        if node.col_offset != node.end_col_offset
                        else str(node.col_offset)
                    )
                return None
            case constants.DISPLAY_ROLE, 4:
                return ast.get_source_segment(self.code, node)
            case constants.FONT_ROLE, 4 | 5:
                return SOURCE_FONT
            case constants.DISPLAY_ROLE, 5:
                try:
                    return ast.get_docstring(node)
                except TypeError:
                    return None
            case self.Roles.NodeRole, _:
                return node
        return None

    def _fetch_object_children(self, item: AstModel.TreeItem) -> list[AstModel.TreeItem]:
        return [self.TreeItem(obj=i) for i in ast.iter_child_nodes(item.obj)]

    def _has_children(self, item: AstModel.TreeItem) -> bool:
        if item.obj is None:
            return False
        return any(True for _ in ast.iter_child_nodes(item.obj))

    def rename_variable(
        self,
        old: str,
        new: str,
        root_tree: ast.AST | None = None,
        ignore: list[str] | None = None,
        scope: list[str] | None = None,
    ):
        """Rename all identifiers named `old` to `new`.

        Arguments:
            old: identifier to rename
            new: new name
            root_tree: tree to modify (default: the tree of the model)
            ignore: names of function / class scopes to leave untouched
            scope: initial scope stack
        """
        top_level = root_tree is None
        root_tree = self.ast_tree if root_tree is None else root_tree
        if root_tree is None:
            return
        self._rename(root_tree, old, new, set(ignore or []), scope or ["main"])
        if top_level:
            self.set_ast(root_tree)

    def _rename(self, node: ast.AST, old: str, new: str, ignore: set[str], scope):
        if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
            scope = [*scope, node.name]
        for field, value in ast.iter_fields(node):
            if isinstance(node, ast.Constant):
                continue
            if value == old and isinstance(value, str) and not set(scope) & ignore:
                setattr(node, field, new)
            for child in value if isinstance(value, list) else [value]:
                if isinstance(child, ast.AST):
                    self._rename(child, old, new, ignore, scope)

    def get_variable_names(self):
        current_names = set()
        if self.ast_tree is None:
            return current_names
        for node in ast.walk(self.ast_tree):
            match node:
                case ast.Name(id=name) | ast.arg(arg=name):
                    current_names.add(name)
        return current_names

rename_variable(old: str, new: str, root_tree: ast.AST | None = None, ignore: list[str] | None = None, scope: list[str] | None = None)

Rename all identifiers named old to new.

Parameters:

Name Type Description Default
old str

identifier to rename

required
new str

new name

required
root_tree AST | None

tree to modify (default: the tree of the model)

None
ignore list[str] | None

names of function / class scopes to leave untouched

None
scope list[str] | None

initial scope stack

None
Source code in prettyqt/itemmodels/astmodel.py
def rename_variable(
    self,
    old: str,
    new: str,
    root_tree: ast.AST | None = None,
    ignore: list[str] | None = None,
    scope: list[str] | None = None,
):
    """Rename all identifiers named `old` to `new`.

    Arguments:
        old: identifier to rename
        new: new name
        root_tree: tree to modify (default: the tree of the model)
        ignore: names of function / class scopes to leave untouched
        scope: initial scope stack
    """
    top_level = root_tree is None
    root_tree = self.ast_tree if root_tree is None else root_tree
    if root_tree is None:
        return
    self._rename(root_tree, old, new, set(ignore or []), scope or ["main"])
    if top_level:
        self.set_ast(root_tree)

set_ast(ast_tree: ast.AST | str = '')

Set an AST tree for the model.

Parameters:

Name Type Description Default
ast_tree AST | str

Abstract syntax tree

''
Source code in prettyqt/itemmodels/astmodel.py
def set_ast(self, ast_tree: ast.AST | str = ""):
    """Set an AST tree for the model.

    Arguments:
        ast_tree: Abstract syntax tree
    """
    match ast_tree:
        case str():
            code = ast_tree
            try:
                node = ast.parse(ast_tree)
            except SyntaxError as e:
                logger.debug("caught %r when building AST", e)
                return
        case ast.AST():
            code = ast.unparse(ast_tree)
            node = ast.parse(code)  # makin a circle to make sure line numbers match.
        case _:
            raise TypeError(ast_tree)
    node = ast.fix_missing_locations(node)
    with self.reset_model():
        self.ast_tree = node
        self._init_root_item(node)
        self.code = code

:fa-brands-github: Show source on GitHub